package com.news.base;

import com.news.util.LogUtil;

import java.lang.ref.Reference;
import java.lang.ref.WeakReference;

import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by Administrator on 2017/3/1 0001.
 */

public class RxPresenter<V extends BaseView> implements BasePresenter<V> {

    private Reference<V> mVReference;
    private CompositeSubscription mCompositeSubscription;

    @Override
    public void attachView(V view) {
        mVReference = new WeakReference<V>(view);
        LogUtil.d("RxPresenter", "attachView: " + view);
    }

    public V getView() {
        if (null != mVReference)
            return mVReference.get();
        return null;
    }

    public boolean isViewAttached() {
        return null != mVReference && null != mVReference.get();
    }

    @Override
    public void detachView() {
        LogUtil.d("RxPresenter", "detachView: ");
        unSubscribe();
        if (mVReference != null) {
            mVReference.clear();
            mVReference = null;
        }
    }

    private void unSubscribe() {
        if (mCompositeSubscription != null) {
            mCompositeSubscription.unsubscribe();
        }
    }

    protected void addSubscribe(Subscription subscription) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(subscription);
    }
}
